/* nbd-queue.c */

#include <stdlib.h>

#include "nbd-queue.h"

void nbd_queue_init(NBD_QUEUE *q)
{
  q->first = q->last = -1;
}

int nbd_queue_has_item(NBD_QUEUE *q)
{
  return q->first >= 0;
}

int nbd_queue_can_add(NBD_QUEUE *q)
{
  return (q->first < 0) || ((q->last + 1) % NBD_QUEUE_LEN != q->first);
}

int nbd_queue_get_item(NBD_QUEUE *q, NBD_REQ *item)
{
  if (q->first < 0)
    return 0;

  *item = q->items[q->first];
  if (q->first == q->last)
    q->first = q->last = -1;
  else
    q->first = (q->first + 1) % NBD_QUEUE_LEN;
  return 1;
}

int nbd_queue_add_item(NBD_QUEUE *q, NBD_REQ *item)
{
  NBD_REQ *req;

  if (q->first < 0)
    q->first = q->last = 0;
  else {
    int next = (q->last + 1) % NBD_QUEUE_LEN;
    if (next == q->first)
      return 0;
    q->last = next;
  }

  req = &q->items[q->last];
  *req = *item;
  return 1;
}

